﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using AgileBoard.Domain;
using AgileBoard.Dtos;
using AgileBoard.Dtos.Mappers;
using AgileBoard.Web.Controllers.Util;

namespace AgileBoard.Web.Controllers
{
    public class StoryController : BaseController
    {
        // POST: /Story/Index/iterationId

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Index(Guid iterationId)
        {
            var rdto = new ResultDTO();

            IList stories = ManagerFactory.StoryManager.GetByIteration(iterationId.ToString());

            IList<StoryDTO> storiesDTO = new List<StoryDTO>();
            foreach (Story story in stories)
            {
                StoryDTO storyDto = StoryDTOMapper.MapToDTO(story);
                storiesDTO.Add(storyDto);
            }

            rdto.Data = storiesDTO.ToExtJsJson("items", "totalCount");
            rdto.Result = true;
            rdto.Message = "Success";

            return Json(rdto);
        }

        // POST: /Story/Update/Json, Update

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Update(StoryDTO Json, Boolean Update)
        {
            var rdto = new ResultDTO();
            Story Story = StoryDTOMapper.MapFromDTO(Json);

            if (!Update)
            {
                Story.StoryID = Guid.Empty;
                Story.Name = "Newz Story";
                Story.CreateTime = DateTime.Now;
            }

            try
            {
                Story = ManagerFactory.StoryManager.Update(Story);
                rdto.Result = true;
                rdto.Message = "Success";
                rdto.Data = StoryDTOMapper.MapToDTO(Story).ToExtJsJson();
            }
            catch (Exception e)
            {
                rdto.Message = e.Message;
                rdto.Result = false;
            }

            return this.Json(rdto);
        }

        // POST: /Story/Delete/GUID

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Delete(Guid Guid)
        {
            var rdto = new ResultDTO();
            try
            {
                IList tasks = ManagerFactory.TaskManager.GetByStory(Guid.ToString());
                foreach (Task task in tasks)
                {
                    task.Story = null;
                    ManagerFactory.TaskManager.Update(task);
                }
                ManagerFactory.StoryManager.Delete(Guid);
                rdto.Message = "Success";
                rdto.Result = true;
            }
            catch (Exception ex)
            {
                rdto.Message = ex.Message;
                rdto.Result = false;
            }
            return Json(rdto);
        }
    }
}